package cn.zebra.dev.common.utils;

import java.nio.charset.StandardCharsets;

/**
 * 加密工具类
 *
 * @author runnable@sina.cn
 */
public final class SecurityUtils {

    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 获得MD5加密字符串
     *
     * @param source 源字符串
     * @return 加密后的字符串
     */
    public static String getMd5(String source) {
        String mdString = null;
        if (source != null) {
            // 关键是这句
            mdString = getMd5(source.getBytes(StandardCharsets.UTF_8));
        }
        return mdString;
    }

    /**
     * 获得MD5加密字符串
     *
     * @param source 源字节数组
     * @return 加密后的字符串
     */
    public static String getMd5(byte[] source) {
        String s = null;

        final int temp = 0xf;
        final int arraySize = 32;
        final int strLen = 16;
        final int offset = 4;
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            md.update(source);
            byte[] tmp = md.digest();
            char[] str = new char[arraySize];
            int k = 0;
            for (int i = 0; i < strLen; i++) {
                byte byte0 = tmp[i];
                str[k++] = HEX_DIGITS[byte0 >>> offset & temp];
                str[k++] = HEX_DIGITS[byte0 & temp];
            }
            s = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }
}